from flask import render_template
from .models import User
from . import db
from . import celery
from . import mail
from . import app

from flask_mail import Message, Mail
from datetime import datetime

# mail = Mail(app)

sender = app.config['MAIL_USERNAME']

@celery.task
def send_email(receiver, template, **kwargs):
    '''
    发送邮件
    '''
    with app.app_context():
        for email_receiver in receiver:
            msg = Message('超腾新闻', sender=sender, recipients=[email_receiver])
            msg.html = render_template(template, **kwargs)
            print('[INFO] mail send to %s' % email_receiver)
            mail.send(msg)


def check_user(email):
    '''
    确认用户唯一性
    '''
    rel = {}
    checker = User.objects(email=email).first()
    if checker:
        return True # 已存在
    else:
        return False # 不存在


def create_user(email, nickname, password):
    '''
    创建新用户
    '''
    new_user = User(email=email,nickname=nickname,identity='ordinary')
    new_user.hash_password(password)
    new_user.save()
    return new_user